package com.zheng.rpc.registry.zk;

import com.zheng.rpc.enums.RpcErrorMessageEnum;
import com.zheng.rpc.exceptions.RpcException;
import com.zheng.rpc.extensions.ExtensionLoader;
import com.zheng.rpc.loadbalance.LoadBalance;
import com.zheng.rpc.registry.ServiceDiscovery;
import com.zheng.rpc.utils.CuratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;

import java.net.InetSocketAddress;
import java.util.List;

@Slf4j
public class ZkDiscovery implements ServiceDiscovery {
    private final LoadBalance loadBalance;

    public ZkDiscovery() {
        this.loadBalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension("loadBalance");
    }

    @Override
    public InetSocketAddress lookupService(String serviceName) {
        CuratorFramework zkClient = CuratorUtil.getZkClient();
        List<String> serviceUrlList = CuratorUtil.getChildrenNodes(zkClient, serviceName);
        if (serviceUrlList.isEmpty()) {
            throw new RpcException(RpcErrorMessageEnum.SERVICE_CAN_NOT_BE_FOUND, serviceName);
        }
        //负载均衡
        String targetUrl = loadBalance.selectServiceAddress(serviceUrlList, serviceName);
        log.info("Successfully found the service address:[{}]", targetUrl);
        String[] socketAddressArray = targetUrl.split(":");
        String host = socketAddressArray[0];
        Integer port = Integer.valueOf(socketAddressArray[1]);
        return new InetSocketAddress(host, port);
    }
}
